import * as types from './mutation-types'
import { Member } from './api'

const state = {
  profile: {}
}

const mutations = {
  [types.SET_PROFILE](state, profile) {
    // persist profile to both local storage and vuex state
    if (profile && 'token' in profile) {
      localStorage.setObject('profile', profile)
      state.profile = profile
    }
  },
  [types.LOGOUT](state) {
    state.profile = null
  }
}

const actions = {
  [types.LOGIN](context, payload) {
    return Member.login(payload).then(profile => {
      context.commit(types.SET_PROFILE, profile)
      return profile
    })
  },
  [types.LOGOUT](context, payload) {
    return Member.logout().then(response => {
      localStorage.removeItem('profile')
      context.commit(types.LOGOUT)
    })
  },
  [types.RELOAD_PROFILE](context) {
    return Member.profile().then(profile => {
      context.commit(types.SET_PROFILE, profile)
    })
  },
  [types.UPDATE_PROFILE](context, payload) {
    return Member.updateProfile(payload).then(profile => {
      context.commit(types.SET_PROFILE, profile)
    })
  }
}

export default {
  state,
  mutations,
  actions
}
